package net.wantongtech.xa.uploadbasicinfo.service;

import cn.com.taiji.common.manager.net.http.binclient.ApiRequestException;
import cn.com.taiji.sdk.comm.LwClientHelper;
import cn.com.taiji.sdk.model.comm.protocol.cdts.expand.EtcExpandTransDownloadRequest;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import net.lingala.zip4j.core.ZipFile;
import net.wantongtech.xa.uploadbasicinfo.config.SCPClientConfig;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.joda.time.LocalDateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.stereotype.Service;
import org.springframework.util.FileSystemUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 下载拓展应用原始交易包
 *
 * @author MaShibo
 * 2021/3/15 0015
 */
@Slf4j
@Service
public class DownloadExpandPackageService {

    @Resource
    private SCPClientConfig scpClientConfig;

    private File allMunicipalDir;

    @PostConstruct
    public void init() {
        String localStorePath = scpClientConfig.getLocalStorePath();
        allMunicipalDir = new File(localStorePath, "MUNICIPAL_OPERATOR");
        if (!allMunicipalDir.exists() && !allMunicipalDir.mkdirs()) {
            throw new IllegalStateException(String.format("文件夹：%s创建失败", allMunicipalDir.getAbsolutePath()));
        }
    }

    public void download(String startDateTimeStr) {
        log.info(startDateTimeStr);
        DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyyMMddHHmm");
        LocalDateTime tmpDateTime = LocalDateTime.parse(startDateTimeStr, dateTimeFormatter);
        List<File> files = Lists.newArrayList();
        LocalDateTime nowDateTime = LocalDateTime.now();
        while (tmpDateTime.compareTo(nowDateTime) < 0) {
            String version = tmpDateTime.toString("yyyyMMddHHmm");
            log.info("版本号：{}", version);
            File rspFile = null;
            try {
                rspFile = downloadExpandTransFile(version);
                files.add(rspFile);
            } catch (ApiRequestException e) {
                log.error(e.getMessage());
                int errCode = e.getErrCode();
                if (errCode == 711 || errCode == 713) {
                    tmpDateTime = tmpDateTime.plusMinutes(5);
                    continue;
                }
            }
            log.info("响应文件：{}", rspFile);
            tmpDateTime = tmpDateTime.plusMinutes(5);
        }

        for (File file : files) {
            try {
                String storePath = file.getAbsolutePath();
                ZipFile zipFile = new ZipFile(file);
                String extractPath = storePath.substring(0, storePath.lastIndexOf('.'));
                boolean noMunicipal = true;
                try {
                    zipFile.extractAll(extractPath);
                    log.info("文件：{}，解压缩完成", file.getName());

                    File firstDir = new File(extractPath);
                    try {
                        File[] municipalDirs = firstDir.listFiles((dir, name) -> name.equals("MUNICIPAL_OPERATOR"));
                        noMunicipal = ArrayUtils.isEmpty(municipalDirs);
                        if (noMunicipal) {
                            continue;
                        }
                        File municipalDir = municipalDirs[0];
                        File[] jsonFiles = municipalDir.listFiles((dir, name) -> name.endsWith(".json"));

                        if (ArrayUtils.isNotEmpty(jsonFiles)) {
                            for (File jsonFile : jsonFiles) {
                                log.info("文件：{}，复制到：{}", jsonFile.getAbsolutePath(), allMunicipalDir.getAbsolutePath());
                                FileUtils.copyFileToDirectory(jsonFile, allMunicipalDir);
                            }
                        }
                    } finally {
                        firstDir.delete();
                    }
                } finally {
                    FileSystemUtils.deleteRecursively(new File(extractPath));
                    if (noMunicipal) {
                        file.delete();
                    }
                }

            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }


    }

    private File downloadExpandTransFile(String version) {
        EtcExpandTransDownloadRequest request = new EtcExpandTransDownloadRequest();
        request.setVersion(version);
        try {
            String fileName = LwClientHelper.prepareFilename(request);
            log.info("请求文件名：{}", fileName);
            return LwClientHelper.downLoad(request, scpClientConfig.getLocalStorePath());
        } catch (IOException e) {
            return downloadExpandTransFile(version);
        }
    }
}
